package com.deer.wms.base.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.base.system.dao.ItemInfoMapper;
import com.deer.wms.base.system.model.Item.*;
import com.deer.wms.base.system.model.http.HttpClientss;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.base.system.service.ItemTypeService;
import com.deer.wms.busine.tactic.model.Batch.BatchTacticDetail;
import com.deer.wms.busine.tactic.model.QC.QcTacticDetail;
import com.deer.wms.busine.tactic.model.Upper.UpperTacticDetailDto;
import com.deer.wms.busine.tactic.service.*;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.StringUtils;
import com.deer.wms.system.manage.model.organization.Organization;
import com.deer.wms.system.manage.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * @author guo
 * @since 2019/11/19
 */
@Service
@Transactional
public class ItemInfoServiceImpl extends SuperServiceImpl<ItemInfoMapper, ItemInfo> implements ItemInfoService {

    @Autowired
    private ItemInfoMapper itemInfoMapper;

    @Autowired
    private BatchTacticService batchTacticService;

    @Autowired
    private BatchTacticDetailService batchTacticDetailService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private ItemTypeService itemTypeService;

    @Autowired
    private QcTacticDetailService qcTacticDetailService;

    @Autowired
    private UpperTacticService upperTacticService;

    @Autowired
    private UpperTacticDetailService upperTacticDetailService;

    @Autowired
    private ItemInfoService itemInfoService;

    @Override
    public List<ItemInfoDto> findList(ItemInfoCriteria criteria) {
        return itemInfoMapper.findList(criteria);
    }

    @Override
    public List<ItemInfo> findByName(String itemName) {
        return itemInfoMapper.findByName(itemName);
    }

    @Override
    public List<ItemInfo> findByCode(String itemCode) {
        return itemInfoMapper.findByCode(itemCode);
    }


    @Override
    public List<ItemInfoDto> itemInfoFindByItemTypeId(Integer itemTypeId) {
        return itemInfoMapper.itemInfoFindByItemTypeId(itemTypeId);
    }

    @Override
    public void deleteByCode(String itemCode) {
        itemInfoMapper.deleteByCode(itemCode);
    }

    @Override
    public String findBatchTacticCode(String itemCode) {
        ItemInfo itemInfo = this.findBy("item_code",itemCode);
        String batchTacticCode = itemInfo.getBatchTacticCode();
        List<BatchTacticDetail> list = batchTacticDetailService.findByBatchTacticCode(batchTacticCode);

        if(list.size()!=14){
            Integer itemTypeId = itemInfo.getItemTypeId();
            ItemType itemType = itemTypeService.getById(itemTypeId);
            if(itemType!=null){
                list = batchTacticDetailService.findByBatchTacticCode(batchTacticCode);
            }
            if(list.size()!=14){
                Integer organizationId = itemInfo.getOrganizationId();
                Organization organization = organizationService.getById(organizationId);
                batchTacticCode = organization.getBatchTacticCode();
                list = batchTacticDetailService.findByBatchTacticCode(batchTacticCode);
                if(list.size()!=14){
                    throw new ServiceException(CommonCode.BATCH_TACTIC_ERROR, "不存在该批次属性，请在物料或物料类型或货主中新建批次属性");
                }
            }
        }
        return batchTacticCode;
    }


    @Override
    public List<BatchTacticDetail> findBatchTacticDetails(String itemCode) {
        ItemInfo itemInfo = this.findBy("item_code",itemCode);
        String batchTacticCode = itemInfo.getBatchTacticCode();
        List<BatchTacticDetail> list = batchTacticDetailService.findByBatchTacticCode(batchTacticCode);

        if(list.size()!=14){
            Integer itemTypeId = itemInfo.getItemTypeId();
            ItemType itemType = itemTypeService.getById(itemTypeId);
            if(itemType!=null){
                list = batchTacticDetailService.findByBatchTacticCode(batchTacticCode);
            }
            if(list.size()!=14){
                Integer organizationId = itemInfo.getOrganizationId();
                Organization organization = organizationService.getById(organizationId);
                batchTacticCode = organization.getBatchTacticCode();
                list = batchTacticDetailService.findByBatchTacticCode(batchTacticCode);
                if(list.size()!=14){
                    throw new ServiceException(CommonCode.BATCH_TACTIC_ERROR, "不存在该批次属性，请在物料或物料类型或货主中新建批次属性");
                }
            }
        }
        return list ;
    }

    @Override
    public List<UpperTacticDetailDto> findUpperTacticDetails(String itemCode) {
        ItemInfo itemInfo = this.findBy("item_code",itemCode);
        String upperTacticCode = itemInfo.getUpperTacticCode();
        List<UpperTacticDetailDto> list = upperTacticDetailService.findByUpperTacticCode(upperTacticCode);

        if (ObjectUtil.isNull(list) || list.size() == 0 ) {
            Integer itemTypeId = itemInfo.getItemTypeId();
            ItemType itemType = itemTypeService.getById(itemTypeId);
            if(ObjectUtil.isNotNull(itemType)){
                String upperTacticCode2 = itemType.getUpperTacticCode();
                list = upperTacticDetailService.findByUpperTacticCode(upperTacticCode2);
            }
        }
        return list;
    }


    @Override
    public List<QcTacticDetail> findQcTacticDetails(String itemCode) {
        ItemInfo itemInfo = this.findBy("item_code",itemCode);
        String qcTacticCode = itemInfo.getQcTacticCode();
        List<QcTacticDetail> list = qcTacticDetailService.findByQcTacticCode(qcTacticCode);

        if(list==null){
            Integer itemTypeId = itemInfo.getItemTypeId();
            ItemType itemType = itemTypeService.getById(itemTypeId);
            if(itemType==null){
                list = qcTacticDetailService.findByQcTacticCode(qcTacticCode);
            }
            if(list==null){
                Integer organizationId = itemInfo.getOrganizationId();
                Organization organization = organizationService.getById(organizationId);
                qcTacticCode = organization.getQcTacticCode();
                list = qcTacticDetailService.findByQcTacticCode(qcTacticCode);
                if(list==null){
                    throw new ServiceException(CommonCode.QC_TACTIC_ERROR);
                }
            }
        }
        return list ;
    }


    @Override
    public void modifyItemState(String itemCode, String sate, CurrentUser currentUser) {
        ItemInfo itemInfo = itemInfoService.findBy("item_code",itemCode);
        itemInfo.setItemStatus(sate);
        super.updateById(itemInfo);
    }

    @Override
    public ItemInfo findBy(String field, String value) {
        QueryWrapper<ItemInfo> qw = new QueryWrapper<>();
        return this.getOne(qw.eq(field, value));
    }

    @Override
    public long findCount(ItemInfoCriteria criteria) {
        return baseMapper.findCount(criteria);
    }

    @Override
    public void saveItemList(Map<String,Object> hashMap) {
        //获取ERP物料（料品）数据
        List<ItemInfo> itemInfos = findByCodes(hashMap);
        //取得ERP的所有物料的物料编码
        List<String> itemCodeList = new ArrayList<>();
        itemInfos.stream().forEach(t->{
            String itemCode = t.getItemCode();
            itemCodeList.add(itemCode);
        });
        LambdaQueryWrapper<ItemInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ItemInfo::getItemCode,itemCodeList);
        //查询数据库中物料数据
        List<ItemInfo> itemInfoList = itemInfoMapper.selectList(queryWrapper);

        //情况1：无数据直接批量新增
        if (itemInfoList.size() == 0){
            //直接批量插入
            int row = itemInfoMapper.insertList(itemInfos);
            if (row <= 0){
                throw new ServiceException(CommonCode.SYSTEM_ERROR, "新增物料失败");
            }
            return;
        }
        List<String> codeList = new ArrayList<>();
        itemInfoList.stream().forEach(t->{
            codeList.add(t.getItemCode());
        });

        //过滤出相同的   走修改
        List<ItemInfo> collect = itemInfos.stream().filter(t -> codeList.contains(t.getItemCode())).collect(Collectors.toList());
        if (collect.size() > 0){
            collect.stream().forEach(t -> {
                if (StringUtils.isNotEmpty(t.getMakeDate())){
                    t.setMakeDate(t.getMakeDate().replace('T',' '));
                }
                if (StringUtils.isNotEmpty(t.getEditDate())){
                    t.setEditDate(t.getEditDate().replace('T',' '));
                }
                //有效期
                if (ObjectUtil.isEmpty(t.getInDate())){
                    t.setInDate(730);
                }
            });
            int row = itemInfoMapper.updateList(collect);
            if (row <= 0){
                throw new ServiceException(CommonCode.SYSTEM_ERROR, "修改物料失败");
            }
        }
        //过滤出不同的， 走新增
        List<ItemInfo> coll = itemInfos.stream().filter(t -> !codeList.contains(t.getItemCode())).collect(Collectors.toList());
        if (coll.size() > 0){
            int row = itemInfoMapper.insertList(coll);
            if (row <= 0){
                throw new ServiceException(CommonCode.SYSTEM_ERROR, "新增物料失败");
            }
        }
    }

    /**
     * 获取物料信息
     * @param hashMap 条件
     * @return
     */
    public List<ItemInfo> findByCodes(Map<String,Object> hashMap){
        List<ItemInfoVo> billList;
        List<ItemInfo> list = new ArrayList<>();
        Map<String, Object> returnMap = HttpClientss.getDateFromERP2("http://61.160.125.186:5555/zp/api/ZpViewItemMaster/Query", HttpMethod.POST, hashMap);
        if (returnMap.get("code")!= null && "200".equals(returnMap.get("code").toString())){
            if (returnMap.get("data")!= null){
                JSONArray jsonArray = JSONArray.parseArray(String.valueOf(returnMap.get("data")));
                billList = JSONObject.parseArray(jsonArray.toJSONString(), ItemInfoVo.class);
                for (ItemInfoVo vo:billList){
                    ItemInfo itemInfo = new ItemInfo();
                    itemInfo.setItemCode(vo.getItemCode());
                    itemInfo.setItemName(vo.getItemName());
                    itemInfo.setItemType(vo.getItemType());
                    itemInfo.setStatus(vo.getStatus());
                    itemInfo.setSpec(vo.getSpec());
                    itemInfo.setOrg(vo.getOrg());
                    itemInfo.setUnitName(vo.getUnitName());
                    itemInfo.setMakeDate(vo.getMakeDate());
                    itemInfo.setEditDate(vo.getEditDate());
                    list.add(itemInfo);
                }
            }else {
                System.out.println("查询ERP单据信息为空！");
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"查询ERP单据信息为空！");
            }
        }else {
            System.out.println("查询ERP单据信息失败！");
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"查询ERP单据信息失败！");
        }
        return list;
    }
}
